package net.easyjava.third.db.utils;

import net.easyjava.tools.object.ObjectTools;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * Created by wxnacy on 16/6/29.
 */
public class DBInsert {
    private Class clazz;
    private Object obj;

    public DBInsert() {
    }

    public DBInsert(Object obj) {
        this.obj = obj;
        this.clazz = obj.getClass();
    }

    public String getSql() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        //INSERT INTO CATEGORY (id, cid, name, status, display_order) VALUES (?,?,?,?,?);
        StringBuffer sql = new StringBuffer("INSERT INTO ");
        String tableName = DBUtils.getTableName(this.clazz);
        sql.append(tableName);

        StringBuffer names = new StringBuffer(" (");
        StringBuffer values = new StringBuffer(") VALUES (");

        Field[] fields = this.clazz.getDeclaredFields();
        //初始化ObjectTools方法
        ObjectTools objectTools = new ObjectTools(this.obj);
        for(Field field:fields){
            String fieldName = field.getName();
            if(!"serialVersionUID".equalsIgnoreCase(fieldName)){
                String colName = DBUtils.getColumn(field);
                names.append(colName);
                names.append(",");
                Object value = objectTools.invokeGetMethod(fieldName);

                if(value instanceof String){
                    values.append("'");
                    values.append(value);
                    values.append("'");
                }else{
                    values.append(value);
                }
                values.append(",");

            }
        }
        String nameStr = names.substring(0,names.lastIndexOf(","));
        String valueStr = values.substring(0,values.lastIndexOf(","));

        sql.append(nameStr);
        sql.append(valueStr);
        sql.append(");");
        return sql.toString();
    }





}
